package com.itx.gatewayx.utils;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 阿里云百炼工具类
 */
@Slf4j
@Component
public class DashScopeUtils {

    @Value("${ai.dashscope.api-key}")
    private String apiKey;

    @Value("${ai.dashscope.model}")
    private String model;

    /**
     * 调用阿里云百炼API进行对话（非流式）
     *
     * @param messages 对话历史消息列表
     * @return AI回复内容
     */
    public String chat(List<com.itx.gatewayx.domain.AIMessage> messages) {
        try {
            Generation generation = new Generation();
            List<Message> dashScopeMessages = convertToDashScopeMessages(messages);
            
            GenerationParam param = GenerationParam.builder()
                    .apiKey(apiKey)
                    .model(model)
                    .messages(dashScopeMessages)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build();
            
            GenerationResult result = generation.call(param);
            
            // 记录思考过程，便于调试
            String reasoningContent = result.getOutput().getChoices().get(0).getMessage().getReasoningContent();
            if (reasoningContent != null && !reasoningContent.isEmpty()) {
                log.debug("AI思考过程: {}", reasoningContent);
            }
            
            // 返回回复内容
            return result.getOutput().getChoices().get(0).getMessage().getContent();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            log.error("调用阿里云百炼API失败", e);
            return "抱歉，AI服务暂时不可用，请稍后再试。";
        }
    }
    
    /**
     * 调用阿里云百炼API进行流式对话
     *
     * @param messages 对话历史消息列表
     * @return 完整的AI回复内容（异步获取）
     */
    public CompletableFuture<String> chatStream(List<com.itx.gatewayx.domain.AIMessage> messages) {
        CompletableFuture<String> future = new CompletableFuture<>();
        
        try {
            Generation generation = new Generation();
            List<Message> dashScopeMessages = convertToDashScopeMessages(messages);
            
            GenerationParam param = GenerationParam.builder()
                    .apiKey(apiKey)
                    .model(model)
                    .messages(dashScopeMessages)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .incrementalOutput(true)
                    .build();
            
            // 创建用于收集完整回复的StringBuilder
            StringBuilder finalContent = new StringBuilder();
            StringBuilder reasoningContent = new StringBuilder();
            
            // 调用流式API
            Flowable<GenerationResult> result = generation.streamCall(param);
            
            // 异步处理流式响应
            result.subscribe(
                // onNext - 处理每个流式响应片段
                message -> {
                    try {
                        String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
                        String content = message.getOutput().getChoices().get(0).getMessage().getContent();
                        
                        if (reasoning != null && !reasoning.isEmpty()) {
                            reasoningContent.append(reasoning);
                            log.debug("AI思考过程片段: {}", reasoning);
                        }
                        
                        if (content != null && !content.isEmpty()) {
                            finalContent.append(content);
                            log.debug("AI回复片段: {}", content);
                        }
                    } catch (Exception e) {
                        log.error("处理流式响应片段失败", e);
                    }
                },
                // onError - 处理错误
                error -> {
                    log.error("流式调用AI服务失败", error);
                    future.completeExceptionally(error);
                },
                // onComplete - 处理完成
                () -> {
                    log.debug("流式调用AI服务完成");
                    if (reasoningContent.length() > 0) {
                        log.debug("AI完整思考过程: {}", reasoningContent.toString());
                    }
                    future.complete(finalContent.toString());
                }
            );
        } catch (Exception e) {
            log.error("初始化流式调用AI服务失败", e);
            future.completeExceptionally(e);
        }
        
        return future;
    }

    /**
     * 将系统消息列表转换为百炼SDK所需的消息格式
     *
     * @param messages 系统消息列表
     * @return 百炼SDK消息列表
     */
    private List<Message> convertToDashScopeMessages(List<com.itx.gatewayx.domain.AIMessage> messages) {
        List<Message> dashScopeMessages = new ArrayList<>();
        
        for (com.itx.gatewayx.domain.AIMessage message : messages) {
            Role role;
            if ("user".equals(message.getRole())) {
                role = Role.USER;
            } else if ("assistant".equals(message.getRole())) {
                role = Role.ASSISTANT;
            } else {
                role = Role.SYSTEM;
            }
            
            Message dashScopeMessage = Message.builder()
                    .role(role.getValue())
                    .content(message.getContent())
                    .build();
            
            dashScopeMessages.add(dashScopeMessage);
        }
        
        return dashScopeMessages;
    }
} 